/**
 *Javascript document
 **/

var seats = null;
var types = null;

function loadInformation(){
    loadSource();
    loadFinal();   
}

function loadSource(){
    var argsArray=new Array();
    argsArray.push(newArg("Action","Source"));
    sendRequest("../controller/controllerTickets.jsp",argsArray,showSource);
}

function loadFinal(){
    var argsArray=new Array();
    argsArray.push(newArg("Action","Final"));
    sendRequest("../controller/controllerTickets.jsp",argsArray,showFinal);
}

function showSource(){
    if (isValidResponse(this))
    {
        var res=this.responseText;       
        if(res!="")
        {           
            var info=eval("("+res+")");            
            if(info.errorcode == 0){
                if(info.data.length<1){
                    jConfirm('No existen ciudades origen disponibles aun', 'Error', 'Error Dialog');
                }else{
                    var selS = document.getElementById("selSource");
                    var selectS = "";
                    for(var i=0; i<info.data.length; i++){
                        selectS+='<option>';
                        selectS+=info.data[i].o+'</option>';
                    }
                    selS.innerHTML = selectS;
                }
            }else
                window.alert("Error");
        }
    }

}

function showFinal(){
    if (isValidResponse(this))
    {
        var res=this.responseText;
        if(res!="")
        {
            var info=eval("("+res+")");
            if(info.errorcode == 0)
            {
                if(info.data.length<1){
                    jConfirm('No existen ciudades destino disponibles aun', 'Error', 'Error Dialog');
                }else{
                    var selF = document.getElementById("selFinal");
                    var selectF = "";
                    for(var i=0; i<info.data.length; i++){
                        selectF+='<option>';
                        selectF+=info.data[i].d+'</option>';
                    }
                    selF.innerHTML = selectF;                   
                }

            }else
                window.alert("Error");
        }
    }   

}

function findTravel(){
    
    var idSource = document.getElementById("selSource").value;
    var idFinal = document.getElementById("selFinal").value;
    var date = document.getElementById("txtDate").value;
    var hour = document.getElementById("txtHour").value;

    if(validateDate(date)){
        if(idSource.toString()=="" || idFinal.toString() == "" || hour=="" || date==""){
            jConfirm('Se deben diligenciar todos los campos', 'Error', 'Error Dialog');
        }else{
            var argsArray=new Array();
            argsArray.push(newArg("Action","find"));
            argsArray.push(newArg("cityS", idSource.toString()));
            argsArray.push(newArg("cityF", idFinal.toString()));
            argsArray.push(newArg("hour", hour));
            argsArray.push(newArg("date", date));
            argsArray.join("&");
            sendRequest("../controller/controllerTickets.jsp",argsArray,showFind);
        }
    }else{
        jConfirm('Fecha anterior al d&iacute;a de hoy. Por favor seleccione otra', 'Error', 'Error Dialog');
    }
    

}

function showFind(){    
    if (isValidResponse(this))
    {
        var res=this.responseText;
        if(res!="")
        {           
            var info=eval("("+res+")");            
          
            if(info.errorcode == 0)
            {                
                seats = new Array();
                types = new Array();
                for(var i=0; i<info.data.length; i++){
                    seats[i] = info.data[i].position;
                    types[i] = info.data[i].type;

                    if(seats[i]<10){
                        seats[i]="0"+seats[i];
                    }

                    if(types[i]=="Reservado"){
                        document.getElementById(seats[i]).className="boxStyleReserved";
                    }else if(types[i]=="Vendido"){
                        document.getElementById(seats[i]).className="boxStyleSold";
                    }
                }
                document.getElementById("form").style.display = "none";
                document.getElementById("formR").style.display = "block";
                
            }else
                jConfirm('No existen viajes programados', 'Error', 'Error Dialog');
        }else{
            jConfirm('Error en la base de datos', 'Error', 'Error Dialog');
            
        }
    }
}

function viewNumber(number){
    if(number<10){
        number = "0"+number;
    }   
    if(document.getElementById(number).className!="boxStyleSold" && document.getElementById(number).className!="boxStyleReserved" )
        document.getElementById("txtPlace").value=number;
    else
        jConfirm('El puesto elegido se encuentra ocupado, Seleccione otro por favor', 'Error', 'Error Dialog');
}

function makeReservation(){

    var position = document.getElementById("txtPlace").value;
    var idSource = document.getElementById("selSource").value;
    var idFinal = document.getElementById("selFinal").value;
    var hour = document.getElementById("txtHour").value;
    var date = document.getElementById("txtDate").value;
    var user = document.getElementById("txtUser").value;

    if(position == "" || idSource.toString()=="" || idFinal.toString() == "" || date=="" || hour==""){
        jConfirm('Debe seleccionar una ubicaci&oacute;n', 'Error', 'Error Dialog');
    }else if(user!=""){
        var argsArray=new Array();
        argsArray.push(newArg("Action","Reservation"));
        argsArray.push(newArg("position", position));
        argsArray.push(newArg("hour", hour));
        argsArray.push(newArg("cityS", idSource.toString()));
        argsArray.push(newArg("cityF", idFinal.toString()));
        argsArray.push(newArg("date", date));
        argsArray.push(newArg("user", user));
        argsArray.join("&");
        sendRequest("../controller/controllerTickets.jsp",argsArray,showReservation);
    }else{
        jConfirm('Debe iniciar sesión para realizar una reservaci&oacute;n', 'Error', 'Error Dialog');
    }
}

function showReservation(){
    if (isValidResponse(this))
    {
        var res=this.responseText;       
        var html = "";
        if(res!="")
        {            
            var info=eval("("+res+")");
            if(info.errorcode == 0)
            {
                var seat = info.data[0].position;
                html="<br><br>";
                html+="<table class='confirm' border='2'>";
                html+="<tr><td colspan=2><p>Informaci&oacute;n reserva</p></td></tr>";
                html+="<tr><td class='conf'>Numero ticket: </td><td class='conf'>"+info.data[0].id+"</td></tr>";
                html+="<tr><td class='conf'>Tipo: </td><td class='conf'>"+info.data[0].type+"</td></tr>";
                html+="<tr><td class='conf'>N&ordm; puesto: </td><td class='conf'>"+seat+"</td></tr>";
                html+="<tr><td class='conf'>Fecha: </td><td class='conf'>"+info.data[0].date+"</td></tr>";
                html+="<tr><td class='conf'>Nombre de usuario: </td><td class='conf'>"+info.data[0].user+"</td></tr>";
                html+="</table>";

                document.getElementById("formR").innerHTML = html;
                if(seat<10){
                    seat="0"+seat;
                    document.getElementById(seat).className="boxStyleReserved";
                }else{
                    document.getElementById(seat).className="boxStyleReserved";
                }

            }else
                window.alert("Error");
        }
    }
}

function getHour(){
    
    var idSource = document.getElementById("selSource").value;
    var idFinal = document.getElementById("selFinal").value;

    if(idSource != idFinal){
        var argsArray=new Array();
        argsArray.push(newArg("Action","hour"));
        argsArray.push(newArg("cityS", idSource.toString()));
        argsArray.push(newArg("cityF", idFinal.toString()));
        argsArray.join("&");
        sendRequest("../controller/controllerTickets.jsp",argsArray,showHour);
    }
}

function showHour(){
    if (isValidResponse(this))
    {
        var res=this.responseText;
        if(res!="")
        {
            var info=eval("("+res+")");
           
            if(info.errorcode == 0){
                
                var selS = document.getElementById("txtHour");
                var selectS = "";
                for(var i=0; i<info.data.length; i++){
                    selectS+='<option>';
                    selectS+=info.data[i].hour+'</option>';
                }
                selS.innerHTML = selectS;
                
            }else
                window.alert("Error");
        }
    }
}

function findTicket(){
    var ticket = document.getElementById("txtTicket").value;
    var user = document.getElementById("txtUser").value;
    if(user!=""){
        if(ticket!=""){
            var argsArray=new Array();
            argsArray.push(newArg("Action","Ticket"));
            argsArray.push(newArg("ticket", ticket));
            argsArray.join("&");
            sendRequest("../controller/controllerTickets.jsp",argsArray,showTicket);
        }else{
            jConfirm('D&iacute;gite el numero del ticket', 'Error', 'Error Dialog')
        }
    }
    else{
        jConfirm('Debe iniciar sesión para realizar una reservaci&oacute;n', 'Error', 'Error Dialog');
    }
}

function showTicket(){
    if (isValidResponse(this))
    {
        var res=this.responseText;
       
        var html = "";
        if(res!="")
        {
            var info=eval("("+res+")");
            if(info.errorcode == 0)
            {
                if(info.data.length<1){
                    jConfirm('Ticket no encontrado', 'Error', 'Error Dialog')
                }else{
                    html="<br><br><center>";
                    html+="<table>";
                    html+="<tr><td colspan=2><p><center><label class='fieldTitle'>Informaci&oacute;n reserva</label></center></p></td></tr>";
                    html+="<tr><td class='conf'><label class='fieldtext'>Numero ticket: </label></td><td class='conf'><input type='text' id='txtId' value="+info.data[0].id+" readonly /></td></tr>";
                    html+="<tr><td class='conf'><label class='fieldtext'>Tipo: </label></td><td class='conf'><input type='text' id='txtType' value="+info.data[0].type+" readonly /></td></tr>";
                    html+="<tr><td class='conf'><label class='fieldtext'>N&ordm; puesto: </label></td><td class='conf'><input type='text' id='txtPos' value="+info.data[0].position+" /></td></tr>";
                    html+="<tr><td class='conf'><label  class='fieldtext'>Fecha: </label></td><td class='conf'><input type='text' id='txtDate' value="+info.data[0].date+" /></td></tr>";
                    html+="<tr><td class='conf'><label  class='fieldtext'>Nombre de usuario: </label></td><td class='conf'><input type='text' id='txtUserN' value="+info.data[0].user+" readonly /></td></tr>";
                    html+="<tr><td class='conf'><center><input type='button' id='btnUpdate' value='Actualizar' class='button_form' onclick='updateTicket()' onkeypress='if(event.keyCode==13){updateTicket();}'/></center></td><td class='conf'><center><input type='button' id='btnDelete' value='Eliminar' class='button_form' onclick='deleteTicket()' onkeypress='if(event.keyCode==13){deleteTicket();}' /></center></td></tr>";
                    html+="</table></center>";

                    document.getElementById("form").innerHTML = html;
                }
            }else if(info.errorcode == -6)
                jConfirm('Ticket no encontrado', 'Error', 'Error Dialog')
        }
    }
}

function updateTicket(){
    var ticket = document.getElementById("txtId").value;    
    var position = document.getElementById("txtPos").value;
    var date = document.getElementById("txtDate").value;
    if(document.getElementById("txtUser").value==document.getElementById("txtUserN").value){
        var argsArray=new Array();
        argsArray.push(newArg("Action","Update"));
        argsArray.push(newArg("ticket", ticket));
        argsArray.push(newArg("position", position));
        argsArray.push(newArg("date", date));
        argsArray.join("&");
        sendRequest("../controller/controllerTickets.jsp",argsArray,showUpdate);

        clean();
    }else{
        jConfirm('No coinciden los usuarios', 'Error', 'Error Dialog')
    }
}

function showUpdate(){
    
    if (isValidResponse(this))
    {
        var res=this.responseText;
        window.alert(res);
        if(res!="")
        {
            var info=eval("("+res+")");
            if(info.errorcode == 0)
            {
                jConfirm('Operaci&oacute;n exitosa', 'Exito', 'Error Dialog');
            }else{
                jConfirm('Ticket actualizado', 'Error', 'Error Dialog');
            }
        }
    }
}

function deleteTicket(){    
    var ticket = document.getElementById("txtId").value;
    if(document.getElementById("txtUser").value==document.getElementById("txtUserN").value){
    var argsArray=new Array();
    argsArray.push(newArg("Action","Delete"));
    argsArray.push(newArg("ticket", ticket));
    argsArray.join("&");
    sendRequest("../controller/controllerTickets.jsp",argsArray,showUpdate);
    clean();
    }else{
      jConfirm('No coinciden los usuarios', 'Error', 'Error Dialog');
    }
}

function clean(){
    document.getElementById("txtId").value="";
    document.getElementById("txtType").value="";
    document.getElementById("txtPos").value="";
    document.getElementById("txtDate").value="";
    document.getElementById("txtUserN").value="";
}